package com.pet.wemedia.controller.v1;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pet.api.wemedia.WmUserControllerApi;
import com.pet.model.common.dtos.PageResponseResult;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.media.dtos.WmUserDto;
import com.pet.model.media.pojos.WmUser;
import com.pet.model.media.pojos.WmUserFriend;
import com.pet.utils.threadlocal.WmThreadLocalUtils;
import com.pet.wemedia.service.WmUserService;
import com.pet.wemedia.service.WmUserFriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/user")
public class WmUserController implements WmUserControllerApi {

    @Autowired
    private WmUserService userService;

    @Autowired
    private WmUserFriendService userFriendService;

    @PostMapping("/page")
    public PageResponseResult page(@RequestBody WmUserDto dto){
        QueryWrapper<WmUser> queryWrapper = new QueryWrapper<WmUser>();
        if(dto.getStatus()!=null){
            queryWrapper.lambda().eq(WmUser::getStatus, dto.getStatus());
        }
        queryWrapper.lambda().orderByDesc(WmUser::getCreatedTime);
        IPage pageParam = new Page(dto.getPage(),dto.getSize());
        IPage iPage = userService.page(pageParam, queryWrapper);
        List records = iPage.getRecords();
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)iPage.getTotal());
        responseResult.setCode(0);
        responseResult.setData(records);
        return responseResult;
    }

    @PostMapping("/save")
    @Override
    public ResponseResult save(@RequestBody WmUser wmUser){
        userService.save(wmUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @PostMapping("/update")
    public ResponseResult update(@RequestBody WmUserDto dto){
        UpdateWrapper<WmUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", dto.getId()); // 设置条件，根据 id 匹配
        updateWrapper.set("status", dto.getStatus()); // 设置要修改的字段和值

        userService.update(updateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @GetMapping("/findByName/{name}")
    @Override
    public WmUser findByName(@PathVariable("name") String name){
        List<WmUser> list = userService.list(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name));
        if(list!=null && !list.isEmpty()){
            return list.get(0);
        }
        return null;
    }

    @GetMapping("/findOne/{id}")
    @Override
    public WmUser findWmUserById(@PathVariable("id") Long id) {
        return userService.getById(id);
    }

    @PostMapping("/bindFriend")
    public ResponseResult bindFriend(@RequestParam("userId") Integer userId, @RequestParam("friendId") Integer friendId) {
        if(userId.equals(friendId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_current_user);
        }
        // 检查用户是否存在
        WmUser user = userService.getById(userId);
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_NOT_EXIST);
        }

        // 检查好友是否存在
        WmUser friend = userService.getById(friendId);
        if (friend == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FRIEND_NOT_EXIST);
        }


        // 检查是否已经绑定
        WmUserFriend userFriend = userFriendService.getOne(Wrappers.<WmUserFriend>lambdaQuery()
                .eq(WmUserFriend::getUserId, userId)
                .eq(WmUserFriend::getFriendId, friendId));
        if (userFriend != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FRIEND_ALREADY_BIND);
        }

        // 创建新的绑定关系
        WmUserFriend newFriend = new WmUserFriend();
        newFriend.setUserId(userId);
        newFriend.setFriendId(friendId);
        newFriend.setCreatedTime(new Date());
        userFriendService.save(newFriend);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @GetMapping("/friendList/{userId}")
    public ResponseResult<List<WmUser>> getFriendList(@PathVariable("userId") Integer userId,@RequestParam(required = false) Integer sharedStatus) {
        // 获取用户的所有好友

        List<WmUserFriend> userFriends = userFriendService.bylist(userId, sharedStatus);

        // 获取好友的详细信息
        List<WmUser> friendInfos = userFriends.stream()
                .map(userFriend -> {
                    WmUser friend = userService.getById(userFriend.getFriendId());
                    return new WmUser(
                            friend.getId(),
                            friend.getName(),
                            friend.getPhone(),
                            userFriend.getSharedStatus()
                    );
                })
                .collect(Collectors.toList());

        return ResponseResult.okResult(friendInfos);
    }

    @PostMapping("/unbindFriend")
    public ResponseResult unbindFriend(@RequestParam("userId") Integer userId, @RequestParam("friendId") Integer friendId) {
        // 检查用户是否存在
        WmUser user = userService.getById(userId);
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_NOT_EXIST);
        }

        // 检查好友是否存在
        WmUser friend = userService.getById(friendId);
        if (friend == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FRIEND_NOT_EXIST);
        }

        // 检查是否已经绑定
        LambdaQueryWrapper<WmUserFriend> wrapper = Wrappers.<WmUserFriend>lambdaQuery()
                .eq(WmUserFriend::getUserId, userId)
                .eq(WmUserFriend::getFriendId, friendId);
        WmUserFriend userFriend = userFriendService.getOne(wrapper);
        if (userFriend == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FRIEND_NOT_BIND);
        }

        // 删除绑定关系
        userFriendService.remove(wrapper);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @PostMapping("/toggleSharedStatus")
    public ResponseResult toggleSharedStatus(@RequestParam("friendId") Integer friendId,@RequestParam("sharedStatus") Integer sharedStatus) {
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 检查好友是否存在
        WmUser friend = userService.getById(friendId);
        if (friend == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FRIEND_NOT_EXIST);
        }

        // 检查是否已经绑定
        WmUserFriend userFriend = userFriendService.getOne(Wrappers.<WmUserFriend>lambdaQuery()
                .eq(WmUserFriend::getUserId, user.getId())
                .eq(WmUserFriend::getFriendId, friendId));
        if (userFriend == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FRIEND_NOT_BIND);
        }

        // 切换共享状态
        userFriend.setSharedStatus(String.valueOf(sharedStatus));
        userFriendService.updateByFriendId(user.getId(),friendId, sharedStatus);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}